//
//  CZComposePictureView.swift
//  微博
//
//  Created by 霸气的刘吉庆 on 16/4/26.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit
import SVProgressHUD
let CZComposeCellID = "compose_cell"


class CZComposePictureView: UICollectionView {
    
    //定义一个数组,提供数据源的方法
    var imagesArray: [UIImage] = []
    
    //定义一个闭包需要的时候进行回调,这个是collectionView的block
    var seletedPicViewCellClosure: (()->())?
    
    //提供给外界一个添加imageView的方法
    func addImage(image: UIImage) {
        
        //判断数量,如果已经有了9张,那么就不添加了,这进行了判断
        if imagesArray.count < 9{
            imagesArray.append(image)
            //刷新数据
            
            reloadData()
            
        }else{
            SVProgressHUD.showErrorWithStatus("数量已达上限")
        }
        
        
        
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
         setupUI()
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //设置界面
        //里面有一个imageView
        
        self.backgroundColor = UIColor.whiteColor()
        
        dataSource = self
        delegate = self
        
        //注册cell
        self.registerClass(CZComposePictureViewCell.self, forCellWithReuseIdentifier: CZComposeCellID)
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置里面空间的约束
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //计算每一个cell的size
        //定义一个margin
        let margin: CGFloat = 5
        let itemWH = (self.frame.width - 2 * margin)/3
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        //设置最小的间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
    }
    

}

extension CZComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        imagesArray.count
        
        //根据图片的有无来判断是否隐藏,没有图片隐藏这个view
        self.hidden = imagesArray.count == 0
        //这个我们让他最多返回的是9张图片,返回的是+1 个
        return imagesArray.count + ((imagesArray.count == 0 || imagesArray.count == 9) ? 0 : 1)
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let  cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZComposeCellID, forIndexPath: indexPath) as! CZComposePictureViewCell
        
        
        //这里来进行判断,是否是最后一张图片
        if indexPath.item == imagesArray.count{
            
            //这个代表的是最后一张
            
            cell.image = nil
            
            
        }else{
        cell.image = imagesArray[indexPath.item]
        }
        
        //设置删除按钮需要执行的闭包,怎么执行呢,注意循环引用
        cell.deleteButtonClosure = {[weak self] in
            //删除对应的元素
            self?.imagesArray.removeAtIndex(indexPath.item)
            self?.reloadData()
     
        }
        
        return cell
        
        
        
    }
    //代理方法,点击cell的时候调用
    //当前的imageArray里面记录的数据是我们实际有的,但是我们事实上还添加了一个数据
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //如果是最后一个cell
        
        if indexPath.item == imagesArray.count {
            //代表最后一个cell被点击了
            //执行闭包,开始回调,这里可以用可选值,进行闭包的调用
            self.seletedPicViewCellClosure?()
        }
        
        
    }
    
    
    
    
    
}


//创建cell,代理方法

class CZComposePictureViewCell: UICollectionViewCell {
    
    //定义一个闭包的属性
    var deleteButtonClosure: (()->())?
    
    
    var image: UIImage? {
        
        didSet{
            if image == nil{
                imageView.image = UIImage(named: "compose_pic_add")
                //这个代表的是添加的cell
                deleteButton.hidden = true
            }else{
            imageView.image = image
                deleteButton.hidden = false
            }
        }
        
        
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //设置界面,里面有一个imageVIew
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        
        //设置imageView的越苏
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        //设置delete的约束
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.trailing.top.equalTo(contentView)
            
        }
        
    }
    
    //懒加载imageView
    
    private lazy var imageView: UIImageView = UIImageView()
    //懒加载一个删除按钮
    private lazy var deleteButton: UIButton = {
       let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
        
    }()
    
    //点击按钮的方法,使用闭包,点击这个按钮,对应的图片消失
    @objc private func deleteButtonClick(){
        deleteButtonClosure?()
        
        
        
        
    }
    
    
    
    
}

